// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID || 'test_openid_001' // 使用测试openId作为后备
  const { orderId, isDamaged = false } = event
  
  console.log('函数开始执行，参数:', event)
  console.log('openId:', openId)
  console.log('orderId:', orderId)
  console.log('isDamaged:', isDamaged)
  
  // 参数校验
  if (!orderId) {
    return {
      code: -1,
      message: '缺少必要参数：orderId'
    }
  }
  
  // 开始数据库事务
  const transaction = await db.startTransaction()
  
  try {
    // 1. 获取订单信息
    console.log('开始查询订单信息')
    const { data: order } = await transaction.collection('orders').doc(orderId).get()
    
    if (!order) {
      await transaction.rollback()
      return {
        code: -1,
        message: '订单不存在'
      }
    }
    
    console.log('获取到订单:', order)
    
    // 2. 检查订单状态
    if (order.status !== '借用中') {
      await transaction.rollback()
      return {
        code: -1,
        message: '该订单不是借用中状态，无法归还'
      }
    }
    
    // 3. 检查用户权限
    if (order.openId !== openId) {
      await transaction.rollback()
      return {
        code: -1,
        message: '无权操作该订单'
      }
    }
    
    // 4. 获取用户信息
    console.log('开始查询用户信息')
    const { data: users } = await transaction.collection('users').where({ openId }).get()
    
    if (users.length === 0) {
      await transaction.rollback()
      return {
        code: -1,
        message: '用户信息不存在'
      }
    }
    
    const user = users[0]
    console.log('获取到用户:', user)
    
    // 5. 获取装备信息
    console.log('开始查询装备信息')
    const { data: equipment } = await transaction.collection('equipment').doc(order.equipmentId).get()
    
    if (!equipment) {
      await transaction.rollback()
      return {
        code: -1,
        message: '装备信息不存在'
      }
    }
    
    console.log('获取到装备:', equipment)
    
    // 6. 计算信用分变动
    const actualReturnTime = db.serverDate()
    const returnDeadline = new Date(order.returnDeadline)
    const now = new Date()
    let creditChange = 0
    let isOverdue = false
    let damagePenalty = 0
    
    if (isDamaged) {
      // 装备损坏，扣除30信用分
      damagePenalty = -30
      console.log('装备损坏，信用分-30')
    }
    
    if (now > returnDeadline) {
      // 逾期归还，信用分减少
      const overdueDays = Math.ceil((now - returnDeadline) / (24 * 60 * 60 * 1000))
      creditChange = -Math.min(overdueDays, 30) // 最多减30分
      isOverdue = true
      console.log(`逾期${overdueDays}天，信用分变动: ${creditChange}`)
    } else {
      // 按时归还，信用分+1
      creditChange = 1
      console.log('按时归还，信用分+1')
    }
    
    // 合并信用分变动
    creditChange += damagePenalty
    
    // 7. 更新订单状态
    console.log('开始更新订单状态')
    await transaction.collection('orders').doc(orderId).update({
      data: {
        status: '已归还',
        actualReturnTime: actualReturnTime,
        creditChange: creditChange,
        isOverdue: isOverdue,
        isDamaged: isDamaged,
        damagePenalty: damagePenalty
      }
    })
    
    // 8. 更新用户信用分
    console.log('开始更新用户信用分')
    const newCreditScore = Math.max(0, user.creditScore + creditChange) // 不低于0分
    await transaction.collection('users').doc(user._id).update({
      data: {
        creditScore: newCreditScore,
        updateTime: db.serverDate()
      }
    })
    
    // 9. 更新装备状态
    console.log('开始更新装备状态')
    await transaction.collection('equipment').doc(equipment._id).update({
      data: {
        status: '可借用',
        currentOrderId: ''
      }
    })
    
    // 提交事务
    console.log('提交事务')
    await transaction.commit()
    
    return {
      code: 0,
      data: {
        creditChange,
        newCreditScore,
        isOverdue,
        isDamaged,
        returnTime: actualReturnTime
      },
      message: generateReturnMessage(isOverdue, isDamaged, creditChange)
    }
  } catch (err) {
    // 发生错误，回滚事务
    console.error('事务错误:', err)
    if (transaction) {
      await transaction.rollback()
    }
    
    return {
      code: -1,
      message: '归还失败: ' + err.message
    }
  }
}

// 生成归还消息
function generateReturnMessage(isOverdue, isDamaged, creditChange) {
  let message = '归还成功';
  
  if (isDamaged && isOverdue) {
    message = `归还成功，装备已损坏且逾期归还，信用分${creditChange}`;
  } else if (isDamaged) {
    message = `归还成功，装备已损坏，信用分-30`;
  } else if (isOverdue) {
    message = `归还成功，但已逾期，信用分${creditChange}`;
  } else {
    message = '归还成功，信用分+1';
  }
  
  return message;
} 